<template>
  <div>
    <!-- 上传到公共模版 -->
    <el-dialog @open="openTemp" title="上传公共库" v-model="isShow" :before-close="closeUploadDialog" :append-to-body="true" width="25%">
      <div v-loading="Dialogloading">
        <el-form :model="uploadInfo" :rules="rules" ref="uploadInfoRef">
          <el-form-item label="公共库模版名称" :label-width="uploadWidth" prop="realName">
            <el-input v-model="uploadInfo.realName" autocomplete="off" placeholder="请输入模版名称"></el-input>
          </el-form-item>

          <el-form-item label="模板分类" :label-width="uploadWidth" prop="parentId">
            <el-select v-model="uploadInfo.parentId" placeholder="请选择模板分类">
              <el-option v-for="(v, i) in leftList" :key="i" :label="v.dictLabel" :value="v.dictValue"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div class="dialog-footer">
          <el-button @click="closeUploadDialog">取 消</el-button>
          <el-button type="primary" @click="submitUpload(uploadInfoRef)">确 定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 上传个人模版 -->
    <el-dialog title="保存模版" v-model="personShow" :append-to-body="true" :before-close="personClose" width="25%">
      <el-form :model="personInfo" :rules="personRules" ref="personInfoRef">
        <el-form-item label="模版名称" :label-width="uploadWidth" prop="realName">
          <el-input v-model="personInfo.realName" clearable placeholder="请输入模版名称"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="personClose">取 消</el-button>
        <el-button type="primary" @click="personUpload(personInfoRef)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
const emit: any = defineEmits(['submitUpload']);
import type { FormInstance } from 'element-plus';
import { ApiTempData, ApiTempCommon, ApiTempPersonal, ApiTempPersonalCommon } from '@/api/personDoc/tempApi';
import { apicreateTemplateCenter } from '@/api/teamKnowdge/teamDocApi';
/*************************************公共start */
const uploadInfoRef = ref<FormInstance>();
const uploadWidth = ref('130px');
const isShow = ref(false);
const Dialogloading = ref(false);
const leftList = ref([]);
const infoData = ref({
  id: ''
});
const uploadInfo = reactive({
  realName: '',
  parentId: ''
});

const rules = reactive({
  realName: [{ required: true, message: '请输入模版名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择模板分类', trigger: 'change' }]
});
const upType = ref(null);

// 上传公共库取消按钮
const closeUploadDialog = () => {
  uploadInfo.realName = '';
  uploadInfo.parentId = '';
  isShow.value = false;
  Dialogloading.value = false;
};

// 获取业务类型选项（左侧导航）
const getleftList = () => {
  let oParam = {
    dictType: 'template_catalogue'
  };

  ApiTempData(oParam).then((res) => {
    if (res.code == 200) {
      leftList.value = res.data;
    }
  });
};

// 上传公共库确定按钮
const submitUpload = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let oParam = {
        state: 'enterprise',
        id: infoData.value.id,
        realName: uploadInfo.realName,
        parentId: uploadInfo.parentId
      };
      if (upType.value == true) {
        //表格上传到公共库
        ApiTempPersonalCommon(oParam).then((res) => {
          closeUploadDialog();
          isShow.value = false;
          ElMessage.success(res.msg);
        });
      } else {
        // 模版中心内部
        ApiTempCommon(oParam).then((res) => {
          // console.log(res, "上传公共库");
          closeUploadDialog();
          isShow.value = false;
          ElMessage.success(res.msg);
          emit('submitUpload');
        });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// ApiTempPersonalCommon
/*************************************公共end */

/*************************************个人start */

const personInfoRef = ref<FormInstance>();
const personRules = reactive({
  realName: [{ required: true, message: '请输入模版名称', trigger: 'blur' }]
});
const personData = ref({} as any);
const personInfo = reactive({
  realName: '',
  parentId: '',
  type: '',
  state: ''
});
const personShow = ref(false);

//上传到个人模版
const personUpload = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let oParam = {
        id: personData.value.id,
        realName: personInfo.realName,
        type: 'team', // 个人：personal 团队：team
        state: 'personal' // （个人模板库：personal 公共模板库：enterprise）
      };
      apicreateTemplateCenter(oParam).then((res) => {
        if (res.code == 200) {
          ElMessage.success(res.msg);
          personShow.value = false;
        } else {
          ElMessage.warning(res.msg);
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 关闭个人模版弹窗
const personClose = () => {
  personShow.value = false;
  personInfo.realName = '';
  personInfo.parentId = '';
};

/*************************************个人end */
const openTemp = () => {
  getleftList();
};

//调用公共模版打开方法
const openPubilshDialog = (val, type) => {
  console.log('🚀 ~ openPubilshDialog ~ type:', type);
  upType.value = type;
  console.log('🚀 ~ 用公共模版打开方法 ~ val:', val);
  infoData.value = val;
  isShow.value = true;
  uploadInfo.parentId = '';
  uploadInfo.realName = '';
};

//调用个人模版打开方法
const personDialog = (val) => {
  personData.value = val;
  console.log('🚀 ~ 调用个人模版打开方法 ~ val:', val);

  personShow.value = true;
  personInfo.parentId = '';
  personInfo.realName = '';
  personInfo.state = 'personal';
  personInfo.state = 'personal';
};
defineExpose({
  //调用组件需要导出 v-model的变量
  openPubilshDialog,
  personDialog
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
